//
//  Status.swift
//  SinaWeibo
//
//  Created by 胡阳 on 16/5/30.
//  Copyright © 2016年 young4ever. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {

    /// 微博创建时间
    var created_at : String? {
        didSet{
            let createDate = NSDate.dateFromString(created_at!)
            
            created_at = createDate.descDate
        }
    }
    
    /// 微博ID
    var id : Int = 0
    
    /// 微博信息内容
    var text : String?
    
    /// 微博来源
    var source : String? {
    
        didSet{
            
            if source == "" {
                return
            }
            
            let sc = source! as NSString
            let location = sc.rangeOfString(">").location + 1
            let len = sc.rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - location
            source = "来自: " + sc.substringWithRange(NSMakeRange(location, len))
        }
    }
    
    /// 配图数组
    var pic_urls : [[String: AnyObject]]? {
        didSet{
        
            storedImageUrls = [NSURL]()
            storedLargeImageUrls = [NSURL]()
            
            for dict in pic_urls! {
                if let urlStr = dict["thumbnail_pic"] as? String
                {
                    storedImageUrls?.append(NSURL(string: urlStr)!)
                    
                    let largeURL = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    
                    // 保存大图的链接
                    storedLargeImageUrls?.append(NSURL(string: largeURL)!)
                }
            }
        }
    }
    
    // 配图的URL数组
    var storedImageUrls : [NSURL]?
    
    // 配图的高清URL数组
    var storedLargeImageUrls : [NSURL]?
    
    
    /// 用户信息
    var user : User?
    
    var retweeted_status : Status?
    
    var pictureUrls : [NSURL]? {
        
        return (retweeted_status == nil) ? storedImageUrls : retweeted_status!.storedImageUrls
    }
    
    var largePictureUrls : [NSURL]? {
        //  返回原创的或者转发的大图链接
        return (retweeted_status == nil) ? storedLargeImageUrls : retweeted_status?.storedLargeImageUrls
    }
    /**
     加载微博数据
     */
    class func loadStatues(since_id: Int,max_id: Int,finished: (models: [Status]?, error: NSError?)->()){
        
        let path = "2/statuses/home_timeline.json"
        var params = ["access_token" : UserAccount.loadAccount()!.access_token!]
        // 下拉刷新
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
        }
        
        // 上拉加载更多
        if max_id > 0 {
            params["max_id"] = "\(max_id - 1)"
        }
        
        NetworkTools.shareNetworkTools().GET(path, parameters: params, success: { (_, JSON) in
            
            
                // 1.将返回的数据中的statuses key对应的数组取出来, 并转换为模型数组
                let models = Status.dict2Model(JSON!["statuses"] as! [[String : AnyObject]])
//                print(JSON)
            
                // 1.1缓存图片
                cacheStatusImages(models, finished: finished)
            
//                // 2.数据的回调
//                finished(models: models, error: nil)
            }) { (_, error) in
                print(error)
                finished(models: nil, error: error)
        }
        
    }
    
    /**
     缓存图片
     */
    class func cacheStatusImages(list: [Status],finished: (models: [Status]?, error: NSError?) ->())
    {
        // 如果没有请求到新的微博, 那么就直接回调结果
        if list.count == 0 {
            finished(models: list, error: nil)
            return
        }
        
        // 创建一个组
        let group = dispatch_group_create()
        
        // 遍历数组,下载图片
        for model in list {
            
            // swift2.0新出的语法, 如果条件为nil , 就会执行else后面的语句
            guard let urls = model.pictureUrls else {
                continue
            }
            
            for url in model.pictureUrls!
            {
                // 进入当前组
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) in
                    // 离开当前组
                    dispatch_group_leave(group)
                })
            }
        }
        
        // 当所有图片下载完毕使用闭包通知调用者
        dispatch_group_notify(group, dispatch_get_main_queue()) { 
            
            finished(models: list, error: nil)
        }
    }
    
    class func dict2Model(list : [[String : AnyObject]]) -> [Status]
    {
        var models = [Status]()
        
        for dict in list
        {
            models.append(Status(dict: dict))
        }
        
        return models;
    }
    
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    // setValuesForKeysWithDictionary 这个方法内部会调用下面这个方法
    override func setValue(value: AnyObject?, forKey key: String) {
        
        // 判断当前key是否为user
        if key == "user" {
            // 根据user这个key创建一个用户模型
            user = User(dict: value as! [String : AnyObject])
            return
        }
        
        // 判断当前key是否为retweeted_status<转发微博>
        if "retweeted_status" == key {
            retweeted_status = Status(dict: value as! [String : AnyObject])
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    var properties = ["created_at", "id", "text", "source", "pic_urls"]
    
    
    override var description: String {
    
        let dict = dictionaryWithValuesForKeys(properties)
        return "\(dict)"
    }
    
}
